package com.dp.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.dp.pub.SysProperty;

public class WeatherReport {
	
	
	/**
	 * 获取SOAP的请求头，并替换其中的标志符号为用户输入的城市
	 * 
	 * 编写者：王景辉
	 * 
	 * @param city
	 *            用户输入的城市名称
	 * @return 客户将要发送给服务器的SOAP请求
	 */
	private static String getSoapRequest(String city) {
		StringBuilder sb = new StringBuilder();
		sb
				.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
						+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
						+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
						+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
						+ "<soap:Body>    <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
						+ "<theCityName>" + city
						+ "</theCityName>    </getWeatherbyCityName>"
						+ "</soap:Body></soap:Envelope>");
		return sb.toString();
	}

	/**
	 * 用户把SOAP请求发送给服务器端，并返回服务器点返回的输入流
	 * 
	 * 编写者：王景辉
	 * 
	 * @param city
	 *            用户输入的城市名称
	 * @return 服务器端返回的输入流，供客户端读取
	 * @throws Exception
	 */
	private static InputStream getSoapInputStream(String city) throws Exception {
		try {
			String soap = getSoapRequest(city);
			if (soap == null) {
				return null;
			}
			URL url = new URL(
					"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestProperty("Content-Length", Integer.toString(soap
					.length()));
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			conn.setRequestProperty("SOAPAction",
					"http://WebXml.com.cn/getWeatherbyCityName");

			OutputStream os = conn.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
			osw.write(soap);
			osw.flush();
			osw.close();

			InputStream is = conn.getInputStream();
			return is;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 对服务器端返回的XML进行解析
	 * 
	 * 编写者：王景辉
	 * 
	 * @param city
	 *            用户输入的城市名称
	 * @return 字符串 用,分割
	 */
	public static String getWeather(String city) {
		try {
			Document doc;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputStream is = getSoapInputStream(city);
			doc = db.parse(is);
			NodeList nl = doc.getElementsByTagName("string");
			StringBuffer sb = new StringBuffer();
			for (int count = 0; count < nl.getLength(); count++) {
				Node n = nl.item(count);
//				System.out.println("n: "+n.getFirstChild());
				if(n.getFirstChild().getNodeValue().equals(InterUtil.rb.getString("src.searchResultNull"))) {
					sb = new StringBuffer("#") ;
					break ;
				}
				sb.append(n.getFirstChild().getNodeValue() + "#\n");
			}
			is.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static List getWeatherDetail(String city) {
		List allweather = new ArrayList();
		try {
			Document doc;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputStream is = getSoapInputStream(city);
			doc = db.parse(is);
			NodeList nl = doc.getElementsByTagName("string");
			StringBuffer sb = new StringBuffer();
			if (nl.getLength() >0){
				for (int count = 0; count < nl.getLength(); count++) {
					Node n = nl.item(count);
					if (n ==null || n.getFirstChild()==null) break;
//					System.out.println("n: "+n.getFirstChild());
					if(n.getFirstChild().getNodeValue().equals("查询结果为空！")) {
						sb = new StringBuffer("#") ;
						break ;
					}
					sb.append(n.getFirstChild().getNodeValue() + "#\n");
				}
			}
			
			is.close();
			is.close();
			//today
			String[] weatherInfos = sb.toString().split("#");
			if(weatherInfos.length < 21) return null;
//			for (int i = 0; i < weatherInfos.length; i++) {
//				System.out.println(i+"---------"+weatherInfos[i]);
//			}
			String date = weatherInfos[6].split(" ")[0];
			String info = weatherInfos[6].split(" ")[1];
			String winfo[] = {"0",weatherInfos[1]+" "+info+" "+weatherInfos[5],weatherInfos[9],weatherInfos[10]+weatherInfos[11]};
			//tomorrow
			String date2 = weatherInfos[13].split(" ")[0];
			String info2 = weatherInfos[13].split(" ")[1];
			String winfo2[] = {"1",weatherInfos[1]+" "+info2+" "+weatherInfos[12],weatherInfos[16]};
			//the day after tomorrow
			String date3 = weatherInfos[18].split(" ")[0];
			String info3 = weatherInfos[18].split(" ")[1];
			String winfo3[] = {"2",weatherInfos[1]+" "+info3+" "+weatherInfos[17],weatherInfos[21]};
//			System.out.println("winfo ===="+date+weatherInfos[1]+" "+info+" "+weatherInfos[5]+weatherInfos[9]);
//			System.out.println("winfo ===="+date2+weatherInfos[12]+" "+info2+" "+weatherInfos[5]+weatherInfos[16]);
//			System.out.println("winfo ===="+date3+weatherInfos[17]+" "+info3+" "+weatherInfos[5]+weatherInfos[21]);
			allweather.add(winfo);
			allweather.add(winfo2);
			allweather.add(winfo3);
			//winfo ====北京 晴 -7℃/2℃0.gif
			//0  ---   北京 晴 -7℃/2℃
			return allweather;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static List getCustomWeather(String city) {
		try {
			List allweather = new ArrayList();
			Document doc;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputStream is = getSoapInputStream(city);
			doc = db.parse(is);
			NodeList nl = doc.getElementsByTagName("string");
			StringBuffer sb = new StringBuffer();
			for (int count = 0; count < 10; count++) {
				Node n = nl.item(count);
				if(n.getFirstChild().getNodeValue().equals("查询结果为空！")) {
					sb = new StringBuffer("#") ;
					break ;
				}
				sb.append(n.getFirstChild().getNodeValue() + "#");
			}
			is.close();
			//today
			String[] weatherInfos = sb.toString().split("#");
			for (int i = 0; i < weatherInfos.length; i++) {
				System.out.println("weatherInfos: "+weatherInfos[i]);
			}
			System.out.println("weatherInfos: "+weatherInfos.length);
			String date = weatherInfos[6].split(" ")[0];
			String info = weatherInfos[6].split(" ")[1];
			String winfo[] = {date,weatherInfos[1]+" "+info+" "+weatherInfos[5],weatherInfos[9],weatherInfos[10]+" "+weatherInfos[11]};
			allweather.add(winfo);
			//tomorrow
			String date2 = weatherInfos[13].split(" ")[0];
			String info2 = weatherInfos[13].split(" ")[1];
			String winfo2[] = {date2,weatherInfos[1]+" "+info2+" "+weatherInfos[5],weatherInfos[16]};
			allweather.add(winfo2);
			//the day after tomorrow
			String date3 = weatherInfos[18].split(" ")[0];
			String info3 = weatherInfos[18].split(" ")[1];
			String winfo3[] = {date3,weatherInfos[1]+" "+info3+" "+weatherInfos[5],weatherInfos[21]};
			allweather.add(winfo3);
			//winfo ====北京 晴 -7℃/2℃0.gif
			//0  ---   北京 晴 -7℃/2℃
			return allweather;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static int getWeatherIcon(String iconname){
		if ("".equals(iconname) || "nothing.gif".equals(iconname)){
			return -1;
		}
		int icon = Integer.valueOf(iconname.substring(0, iconname.indexOf(".")));
		int startindex = Integer.valueOf(SysProperty.getPrep("sysweathericon_startindex_value"));
		int result =-1;
		switch (icon) {
		case 0:
			result =startindex;
			break;
		case 1:
			result =startindex+1;
			break;
		case 2:
			result =startindex+2;
			break;
		//阵雨
		case 3:
		//小雨	
		case 7:
		//中雨
		case 8:
		//大雨
		case 9:
		//暴雨
		case 10:
		//大暴雨
		case 11:
		//特大暴雨
		case 12:
		case 19:
		case 21:
		case 22:
		case 23:
		case 24:
		case 25:
			result =startindex+3;
			break;
		//雷阵雨
		case 4:
		//雷阵雨并伴有冰雹	
		case 5:
			result =startindex+4;
			break;
		//雨夹雪
		case 6:
			result =startindex+5;
			break;
		
		//雾	
		case 18:
			result =startindex+6;
			break;
//		case 19:
//			result =startindex+7;
//			break;
		//沙尘暴
		case 20:
		case 31:
			result =startindex+7;
			break;
			
		
		//扬沙
		case 29:
		case 30:
			result =startindex+8;
			break;
		
		case 13:
		case 14:
		case 15:
		case 16:
		case 17:
		case 26:
		case 27:
		case 28:
			result =startindex+9;
			break;
		default:
			result =-1;
			break;
		}
		return result;
	}
	/**
	 * 测试用
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
//		System.out.println(getWeatherDetail("北京"));
		List list =  getWeatherDetail("北京");
		if(list !=null &&list.size() >0){
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				String wws[] = (String[]) iterator.next();
				int icon = getWeatherIcon(WeatherReport.relpaceString(wws[2]));
				System.out.println(icon+"  ---   "+WeatherReport.relpaceString(wws[0]));
				Thread.sleep(500);
			}
		}
		

	}
	
	public static String relpaceString (String str){
		Pattern p = Pattern.compile("\t|\r|\n");  
		Matcher m = p.matcher(str);  
		String after = m.replaceAll(""); 
		return after;
	}
}
